import { all, call,delay, fork, put, select, take, takeEvery } from 'redux-saga/effects'
import * as actions from '../actions/productAction'
import * as actionTypes from '../actionTypes'
import { api } from '../../services'
import { getCart } from '../reducers'

function* incrementAsync() {
  yield delay(1000);
  yield put({type: 'INCREMENT'});
}

function* watchInCrementAsync() {
  yield takeEvery('INCREMENT_ASYNC1', incrementAsync)
}

function* decrementAsync() {
  yield delay(2000);
  yield put({type: 'DECREMENT'});
}

function* watchDeCrementAsync() {
  yield takeEvery('DECREMENT_ASYNC1', decrementAsync)
}

function* getAllProducts() {
  const products = yield call(api.getProducts)
  // put 类似于dispatch, 发起action
  yield put(actions.receiveProducts(products))
}

// 一直没搞懂 为什么会直接发起了GET_ALL_PRODUCTS的action,
// 这不应该是监听action 收到了GET_ALL_PRODUCTS这个，才会调用getAllProducts去获取数据吗
// 怎么一进来就获取数据了。。
export function* watchGetProducts() {
  yield takeEvery(actionTypes.GET_ALL_PRODUCTS, getAllProducts)
}

function* checkout() {
  try {
    // 获取购物车数据
    const cart = yield select(getCart)
    // 发起请求
    yield call(api.buyProducts, cart);
    // 结算成功
    yield put(actions.checkoutSuccess(cart))
  } catch (error) {
    // 结算失败
    yield put(actions.checkoutFailure(error))
  }
}

export function* watchCheckout() {
  while (true) {
    yield take(actionTypes.CHECKOUT_REQUEST);
    yield call(checkout)
  }
}

export function* rootSaga() {
  yield all([
    // 购物车
    fork(getAllProducts),
    fork(watchGetProducts),
    fork(watchCheckout),
    // 计数器
    watchInCrementAsync(),
    watchDeCrementAsync()
  ])
}
